<?php

// Functie om makkelijker de namen even values te krijgen vanuit de resultset van het SugarCRM
function nameValuePairToSimpleArray($array)
{
    $my_array = array();
    while(list($name,$value)=each($array))
    {
        $my_array[$value['name']]=$value['value'];
    }
	
    return $my_array;
}

//Functie om makkelijk alle velden van een (opgegeven)module op te vragen
function getModuleFields($arg_Modulenaam)
{
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
    $session_id = $_SESSION['session'];
	
	
	$set_entry_params = array(
		                      'session' => $session_id,
							  'module_name' => $arg_Modulenaam
							  );
	$result = $sugar_client->call('get_module_fields',$set_entry_params);

    return $result;
}

function getAModules()
{
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
    $session_id = $_SESSION['session'];

	$result = $sugar_client->call('get_available_modules',$session_id);

    return $result;
}

function generatePassword($length)
{
  $password = "";
  $possible = "0123456789abcdfghjkmnpqrstvwxyz";
   
  $i = 0; 
  while ($i < $length)
  {
	  $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
	  if(!strstr($password, $char))
	  {
		  $password .= $char;
		  $i++;
	  }
  }
  
  return $password;
}

function sendConfirmationMail($arg_obj, $arg_password, $arg_type)
{
	//echo('<br />sendConfirmationMail('.$arg_student.', '.$arg_password.')');
	
	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

	// Additional headers
	$headers .= 'To: '.$arg_obj->getFullName().' <'.$arg_obj->getEmail().'>'."\r\n";
	$headers .= 'From: Hogeschool Utrecht <noreply@hu.nl>' . "\r\n";
	
	$onderwerp='';
	
	if($arg_type == 'new')
	{
		$message=
		nl2br(
		"
			Beste ".$arg_obj->getFullName().",
			
			Bedankt voor uw aanmelding.
			Uw gebruikersnaam is: ".$arg_obj->getEmail()."
			Uw wachtwoord is: ".$arg_password."
			
			
			Met vriendelijke groet,
			
			Hogeschool Utrecht
		");
		$subject = 'Bedankt voor uw registratie bij Stage frontend!';
	}
	elseif($arg_type == 'change')
	{
		$message=
		nl2br(
		"
			Beste ".$arg_obj->getFullName().",
			
			Uw gebruikersaccount bij de stage frontend is gewijzigd.
			Uw gebruikersnaam is vanaf heden: ".$arg_obj->getEmail()."
			Uw wachtwoord is vanaf heden: ".$arg_password." (deze kunt u weer wijzigen op de frontend)
			
			Met vriendelijke groet,
			
			Hogeschool Utrecht
		");
		
		 $subject = 'Wijziging account bij Stage frontend!';
	}
	
	mail($arg_obj->getEmail(), $subject, $message, $headers);
}

function sendAdministratieConfirmationMail($arg_username, $arg_password, $arg_voornaam, $arg_achternaam, $arg_tussenvoegsel)
{
	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

	if($arg_tussenvoegsel =='')
	{
		$fullname= $arg_voornaam.' '.$arg_achternaam;
	}
	else
	{
		$fullname= $arg_voornaam.' '.$arg_tussenvoegsel.' '.$arg_achternaam;
	}

	// Additional headers
	$headers .= 'To: '.$fullname.' <'.$arg_username.'>'."\r\n";
	$headers .= 'From: Hogeschool Utrecht <noreply@hu.nl>' . "\r\n";
	
	
	
	$message=
		nl2br(
		"
			Beste ".$fullname.",
			
			Bedankt voor uw aanmelding.
			Uw gebruikersnaam is: ".$arg_username."
			Uw wachtwoord is: ".$arg_password."
			
			
			Met vriendelijke groet,
			
			Hogeschool Utrecht
		");
	
	$subject = 'Bedankt voor uw registratie bij Stage frontend!';
	
	mail($arg_username, $subject, $message, $headers);
}

function getRole($arg_rolnaam)
{
	//echo('<br />getRole('.$arg_rolnaam.')');
	
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
	$session_id =$_SESSION['session'];

	//Get Role id
	$set_entry_params = array(
							  'session' => $session_id,
							  'module_name' => 'Roles',
							  'query' => 'acl_roles.name = \''.$arg_rolnaam.'\'',
							  'order_by' => '',
							  'select_fields'=>array(
														'id',
														'name'
													 ),
							  'deleted' => false
							  );

	$result = $sugar_client->call('get_entry_list', $set_entry_params);
	
	if($result['error']['name'] == 'No Error')
	{
		foreach($result['entry_list'] as $record)
		{
			$array = nameValuePairToSimpleArray($record['name_value_list']);
			return $role_id = $array['id'];
			break;
		}
	}
	
	return NULL;
}

function createRelatie($arg_module1, $arg_module1_id, $arg_module2, $arg_module2_id)
{
	//echo('<br />createRelatie('.$arg_module1.', '.$arg_module1_id.', '.$arg_module2.', '.$arg_module2_id.')');
	
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
	$session_id =$_SESSION['session'];
		
	$set_relationship_values = array(
									'module1' => $arg_module1,
									'module1_id' => $arg_module1_id,
									'module2' => $arg_module2,
									'module2_id' => $arg_module2_id
										);
		
		$set_relationship_params = array(
									'session' => $session_id,
									'set_relationship_value' => $set_relationship_values
										);
				
		$result = $sugar_client->call('set_relationship', $set_relationship_params);

		if($result['name'] == 'No Error')
		{
			return true;
			break;
		}
		return false;
}

function createUser($arg_type, $arg_user_name, $arg_pass, $arg_id)
{
	//echo('<br />createUser('.$arg_type.', '.$arg_user_name.', '.$arg_user_name.', '.$arg_id.')');
	$session_id = $_SESSION['session'];
	
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
	
	//Create User
	$set_entry_params = array(
		'session' => $session_id,
		'module_name' => 'Users',
		'name_value_list'=>array(
								array('name'=>'user_name','value'=>$arg_user_name),
								array('name'=>'user_hash','value'=>$arg_pass),
								array('name'=>'last_name', 'value'=>$arg_type),
								array('name'=>'is_group', 'value'=>0),
								array('name'=>'status', 'value'=>'Active'),
								array('name'=>'reports_to_id','value'=>$arg_id)
								)
						  );
	
	$result = $sugar_client->call('set_entry', $set_entry_params);

	if($result['error']['name'] == "No Error")
	{
		return $result['id'];
	}
	
	return NULL;
}

function wijzigWachtwoord($arg_password)
{
	//echo('<br />changePassword('.$arg_password.')');

	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
	$session_id = $_SESSION['session'];
	
	$user_name;
	$last_name;
	
	$user_id = getCurrentUserId();
	$result = getUser($user_id);
		
	foreach($result['entry_list'] as $record)
	{
		$array = nameValuePairToSimpleArray($record['name_value_list']);
		$user_name = $array['user_name'];
		$last_name = $array['last_name'];
	}
	
	$auth_array = array
	(
		'user_auth' => array
		(
			'user_name' => 'admin',
			'password' => md5('welkom')
		)
	);

	$login_results = $sugar_client->call('login', $auth_array);
	
	if($login_results['error']['name']=="No Error")
	{
         $session_id = $login_results['id'];
	}
	
	$set_entry_params = array
	(
		'session' => $session_id,
		'module_name' => 'Users',
		'name_value_list'=>array
		(
		 	array('name'=>'id','value'=>$user_id),
		 	array('name'=>'user_name','value'=>$user_name),
			array('name'=>'user_hash','value'=>md5($arg_password)),
			array('name'=>'last_name','value'=>$last_name)
		)
	);
	
	$result = $sugar_client->call('set_entry', $set_entry_params);
	
	if($result['name'] == "No Error")
	{
		return $result['id'];
	}
	
	return NULL;
}

function getCurrentUserId()
{
	//echo('<br />getCurrentUserId()');
	$session_id = $_SESSION['session'];
	
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
	$user_id = $sugar_client->call('get_user_id', $session_id);
	
	return $user_id;
}

function getUser($user_id)
{
	//echo('<br />getUser()');
	$session_id = $_SESSION['session'];
	
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
	
	//Create User
	$set_entry_params = array(
		'session' => $session_id,
		'module_name' => 'Users',
		'id' => $user_id,
		'select_fields'=>array(
								'user_name',
								'user_hash',
								'last_name',
								'reports_to_id'
								)
						  );
	
	$result = $sugar_client->call('get_entry', $set_entry_params);

	if($result['error']['name'] == "No Error")
	{
		return $result;
	}
	
	return NULL;
}

function getUserId($arg_id)
{
	//echo('<br />getUserId()');
	
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
	
	//Get UserId
	$set_entry_params = array(
							  'session' => getAdminSession(),
							  'module_name' => 'Users',
							  'query' => 'reports_to_id = \''.$arg_id.'\'',
							  'order_by' => '',
							  'select_fields'=>array(
														'id',
													 ),
							  'deleted' => false
							  );

	$result = $sugar_client->call('get_entry_list', $set_entry_params);
	
	if($result['error']['name'] == 'No Error')
	{
		foreach($result['entry_list'] as $record)
		{
			$array = nameValuePairToSimpleArray($record['name_value_list']);
			return $array['id'];
			break;
		}
	}
	
	return NULL;
}

function getAdminSession()
{
	//echo('<br />getAdminSession()');
	
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
	
	$session_id = $_SESSION['session'];
	
	$auth_array = array
	(
		'user_auth' => array
		(
			'user_name' => 'admin',
			'password' => md5('welkom')
		)
	);

	$login_results = $sugar_client->call('login', $auth_array);
	
	if($login_results['error']['name']=="No Error")
	{
         $session_id = $login_results['id'];
	}
	
	return $session_id;
}

function getStudentFromStudenNr($arg_student_nr)
{
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
	
	//echo('<br />getStudentFromStudenNr()');
	$session_id = $_SESSION['session'];
	$set_entry_params = array(
								  'session' => $session_id,
								  'module_name' => 'st_Student',
								  'query' => ' student_nr = \''.$arg_student_nr.'\'',
								  'order_by' => '',
								  'select_fields'=>array(
															'id',
															'student_nr',
															'name',
															'last_name',
															'betweentf',
															'education',
															'active'
														),
								  'deleted' => false
								  );
	
	//Parse de "ruwe" data naar objecten en geef deze vervolgens terug
	$parser = new Parser($wsdl);
	$result = $sugar_client->call('get_entry_list',$set_entry_params);
	
	$parser->setResult($result);
					   
	$student = $parser->getStudentArray();
	return $student[0];
}

function getDocentFromStamNr($arg_stam_nr)
{
	global $wsdl;
	$sugar_client = new nusoapclient($wsdl, true);
	
	//echo('<br />getStudentFromStudenNr()');
	$session_id = $_SESSION['session'];
	$set_entry_params = array(
								  'session' => $session_id,
								  'module_name' => 'st_Docent',
								  'query' => 'stamnummer = \''.$arg_stam_nr.'\'',
								  'order_by' => '',
								  'select_fields'=>array(
															'id',
															'stamnummer',
															'name',
															'lastname',
															'betweentf',
															'functiontf',
															'phone_number',
															'education',
															'active'
														),
								  'deleted' => false
								  );
	
	//Parse de "ruwe" data naar objecten en geef deze vervolgens terug
	$parser = new Parser($wsdl);
	$result = $sugar_client->call('get_entry_list',$set_entry_params);
	
	$parser->setResult($result);
					   
	$docent = $parser->getDocentArray();
	return $docent[0];
}

?>